from django.shortcuts import render, redirect, HttpResponse
from hot.forms.account import LoginForm
from django.http import JsonResponse
from hot import models


def home(request):
    admin_nums = models.Administrator.objects.all().count()
    category_nums = models.Category.objects.all().count()
    img_nums = models.ImgModel.objects.all().count()
    title_nums = models.ContentManage.objects.all().count()
    msg_nums = models.Message.objects.all().count()
    context = {
        'admin_nums': admin_nums,
        'category_nums': category_nums,
        'img_nums': img_nums,
        'title_nums': title_nums,
        'msg_nums': msg_nums,
    }
    return render(request, 'index/index.html', {'context': context})


def welcome(request):
    return render(request, 'index/welcome.html')


def login(request):
    """登录"""
    if request.method == 'GET':
        form = LoginForm()
        return render(request, 'account/login.html')

    form = LoginForm(data=request.POST)
    if not form.is_valid():
        return JsonResponse({'code': -1, 'msg': '用户名或密码错误'})
    # 保存到session
    request.session['user_info'] = {
        'username': form.cleaned_data['username'],
        'role': 'ADMIN'
    }
    return JsonResponse({'code': 200, 'msg': '登录成功', 'data': '/home/'})


def logout(request):
    """退出登录"""
    request.session.clear()
    return redirect('login')


def global_setting(request):
    return render(request, 'manage/sys-set.html')





